package top.soeasy.framework.security.handle;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import top.soeasy.common.constant.HttpStatus;
import top.soeasy.common.core.domain.AjaxResult;
import top.soeasy.common.core.domain.model.BaseLoginUser;
import top.soeasy.common.core.domain.model.LoginUser;
import top.soeasy.common.core.domain.model.MiniLoginMember;
import top.soeasy.common.utils.ServletUtils;
import top.soeasy.common.utils.StringUtils;
import top.soeasy.framework.web.service.TokenService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("successHandler")
public class MobileCodeAuthenSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    private TokenService tokenService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

        BaseLoginUser user = (MiniLoginMember)authentication.getPrincipal();
        String token = tokenService.createToken(user);
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success().put("token",token)));
    }
}
